package com.zhss.demo.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * @author xuhua
 * @create 2021-11-27 18:52
 * @description Volatile测试类
 */
public class VolatileDemo {

    /**
     * 共享变量
     */
    static volatile int flag = 0;

    public static void main(String[] args) {

        /**
         * 整体思路是：上面一个线程读取到下面一个线程修改之后的flag的值
         */
        new Thread() {

            @Override
            public void run() {
                int localFlag = flag;
                while (true) {
                    if (localFlag != flag) {
                        System.out.println("读取到了修改后的标志位：" + flag);
                        localFlag = flag;
                    }
                }
            }

            ;

        }.start();

        new Thread() {

            @Override
            public void run() {
                int localFlag = flag;
                while (true) {
                    System.out.println("标志位被修改为了：" + ++localFlag);
                    flag = localFlag;
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            ;

        }.start();
    }
}
